// 游戏设置
const GAME_WIDTH = 360;
const GAME_HEIGHT = 640;
const LANE_WIDTH = GAME_WIDTH / 3;
const CAT_WIDTH = 70;
const CAT_HEIGHT = 90;
const CHICKEN_WIDTH = 60;
const CHICKEN_HEIGHT = 60;
const MCDONALD_WIDTH = 40;
const MCDONALD_HEIGHT = 40;
const COLA_WIDTH = 30;
const COLA_HEIGHT = 50;
const BULLET_WIDTH = 10;
const BULLET_HEIGHT = 20;
const GAME_SPEED = 3;
const SPAWN_RATE = 60; // 每隔多少帧生成一个物体
const STATUS_BAR_HEIGHT = 25; // 状态栏高度

// 游戏状态
let gameRunning = false;
let health = 3;
let bullets = 10;
let score = 0;
let frameCount = 0;

// 游戏对象
let cat = null;
let chickens = [];
let mcdonalds = [];
let colas = [];
let playerBullets = [];

// 获取DOM元素
const startScreen = document.getElementById('game-start');
const startButton = document.getElementById('start-button');
const gameOverScreen = document.getElementById('game-over');
const restartButton = document.getElementById('restart-button');
const canvasContainer = document.getElementById('game-canvas-container');
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
const healthDisplay = document.getElementById('health');
const bulletsDisplay = document.getElementById('bullets');
const scoreDisplay = document.getElementById('score');
const finalScoreDisplay = document.getElementById('final-score');
const statusBar = document.querySelector('.device-status-bar');

// 设置画布尺寸
canvas.width = GAME_WIDTH;
canvas.height = GAME_HEIGHT;

// 预加载图片
const images = {
    cat: new Image(),
    chicken: new Image(),
    mcdonald: new Image(),
    cola: new Image()
};

images.cat.src = 'pictures/胖猫2.jpg';
images.chicken.src = 'pictures/叮咚鸡.jpg';
images.mcdonald.src = 'pictures/麦当劳.png';
images.cola.src = 'pictures/可乐.png';

// 游戏对象类
class GameObject {
    constructor(x, y, width, height, speed, image) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.speed = speed;
        this.image = image;
    }

    draw() {
        ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
    }

    update() {
        this.y += this.speed;
    }

    isOutOfBounds() {
        return this.y > GAME_HEIGHT;
    }

    collidesWith(other) {
        return !(
            this.x > other.x + other.width ||
            this.x + this.width < other.x ||
            this.y > other.y + other.height ||
            this.y + this.height < other.y
        );
    }
}

class Cat extends GameObject {
    constructor() {
        super(
            GAME_WIDTH / 2 - CAT_WIDTH / 2,
            GAME_HEIGHT - CAT_HEIGHT - 10,
            CAT_WIDTH,
            CAT_HEIGHT,
            0,
            images.cat
        );
        this.lane = 1; // 0, 1, 2 分别代表左中右
    }

    moveLeft() {
        if (this.lane > 0) {
            this.lane--;
            this.x = this.lane * LANE_WIDTH + (LANE_WIDTH - CAT_WIDTH) / 2;
        }
    }

    moveRight() {
        if (this.lane < 2) {
            this.lane++;
            this.x = this.lane * LANE_WIDTH + (LANE_WIDTH - CAT_WIDTH) / 2;
        }
    }

    shoot() {
        if (bullets > 0) {
            bullets--;
            bulletsDisplay.textContent = bullets;
            return new Bullet(this.x + this.width / 2 - BULLET_WIDTH / 2, this.y);
        }
        return null;
    }
}

class Chicken extends GameObject {
    constructor(lane) {
        super(
            lane * LANE_WIDTH + (LANE_WIDTH - CHICKEN_WIDTH) / 2,
            -CHICKEN_HEIGHT,
            CHICKEN_WIDTH,
            CHICKEN_HEIGHT,
            GAME_SPEED,
            images.chicken
        );
    }
}

class McDonald extends GameObject {
    constructor(lane) {
        super(
            lane * LANE_WIDTH + (LANE_WIDTH - MCDONALD_WIDTH) / 2,
            -MCDONALD_HEIGHT,
            MCDONALD_WIDTH,
            MCDONALD_HEIGHT,
            GAME_SPEED,
            images.mcdonald
        );
    }
}

class Cola extends GameObject {
    constructor(lane) {
        super(
            lane * LANE_WIDTH + (LANE_WIDTH - COLA_WIDTH) / 2,
            -COLA_HEIGHT,
            COLA_WIDTH,
            COLA_HEIGHT,
            GAME_SPEED,
            images.cola
        );
    }
}

class Bullet extends GameObject {
    constructor(x, y) {
        super(
            x,
            y,
            BULLET_WIDTH,
            BULLET_HEIGHT,
            -6, // 负数表示向上移动
            null
        );
    }

    draw() {
        ctx.fillStyle = '#FF0000';
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }

    isOutOfBounds() {
        return this.y < -this.height;
    }
}

// 初始化游戏
function initGame() {
    cat = new Cat();
    chickens = [];
    mcdonalds = [];
    colas = [];
    playerBullets = [];
    health = 3;
    bullets = 10;
    score = 0;
    frameCount = 0;
    
    healthDisplay.textContent = health;
    bulletsDisplay.textContent = bullets;
    scoreDisplay.textContent = score;
}

// 生成游戏物体
function spawnObjects() {
    if (frameCount % SPAWN_RATE === 0) {
        const lane = Math.floor(Math.random() * 3);
        const objectType = Math.random();
        
        if (objectType < 0.6) {
            chickens.push(new Chicken(lane));
        } else if (objectType < 0.8) {
            mcdonalds.push(new McDonald(lane));
        } else {
            colas.push(new Cola(lane));
        }
    }
}

// 更新游戏状态
function update() {
    // 更新子弹位置
    playerBullets.forEach(bullet => bullet.update());
    playerBullets = playerBullets.filter(bullet => !bullet.isOutOfBounds());

    // 更新物体位置
    chickens.forEach(chicken => chicken.update());
    mcdonalds.forEach(mcdonald => mcdonald.update());
    colas.forEach(cola => cola.update());

    // 移除超出屏幕的物体
    chickens = chickens.filter(chicken => !chicken.isOutOfBounds());
    mcdonalds = mcdonalds.filter(mcdonald => !mcdonald.isOutOfBounds());
    colas = colas.filter(cola => !cola.isOutOfBounds());

    // 检测碰撞
    // 子弹与叮咚鸡的碰撞
    for (let i = playerBullets.length - 1; i >= 0; i--) {
        for (let j = chickens.length - 1; j >= 0; j--) {
            if (playerBullets[i].collidesWith(chickens[j])) {
                score += 10;
                scoreDisplay.textContent = score;
                playerBullets.splice(i, 1);
                chickens.splice(j, 1);
                break;
            }
        }
    }

    // 猫与叮咚鸡的碰撞
    for (let i = chickens.length - 1; i >= 0; i--) {
        if (cat.collidesWith(chickens[i])) {
            health--;
            healthDisplay.textContent = health;
            chickens.splice(i, 1);
            
            if (health <= 0) {
                gameOver();
                return;
            }
        }
    }

    // 猫与麦当劳的碰撞
    for (let i = mcdonalds.length - 1; i >= 0; i--) {
        if (cat.collidesWith(mcdonalds[i])) {
            health++;
            healthDisplay.textContent = health;
            mcdonalds.splice(i, 1);
        }
    }

    // 猫与可乐的碰撞
    for (let i = colas.length - 1; i >= 0; i--) {
        if (cat.collidesWith(colas[i])) {
            bullets += 5;
            bulletsDisplay.textContent = bullets;
            colas.splice(i, 1);
        }
    }
}

// 绘制游戏
function draw() {
    // 清除画布
    ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
    
    // 绘制背景
    ctx.fillStyle = '#87CEEB'; // 天空蓝
    ctx.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
    
    // 绘制云朵动画
    const cloudOffset = (frameCount * 0.5) % GAME_WIDTH;
    
    ctx.fillStyle = 'white';
    // 第一组云朵
    ctx.beginPath();
    ctx.arc((50 + cloudOffset) % GAME_WIDTH, 50, 20, 0, Math.PI * 2);
    ctx.arc((70 + cloudOffset) % GAME_WIDTH, 40, 25, 0, Math.PI * 2);
    ctx.arc((90 + cloudOffset) % GAME_WIDTH, 50, 20, 0, Math.PI * 2);
    ctx.fill();
    
    // 第二组云朵
    ctx.beginPath();
    ctx.arc((250 + cloudOffset * 0.7) % GAME_WIDTH, 80, 20, 0, Math.PI * 2);
    ctx.arc((270 + cloudOffset * 0.7) % GAME_WIDTH, 70, 25, 0, Math.PI * 2);
    ctx.arc((290 + cloudOffset * 0.7) % GAME_WIDTH, 80, 20, 0, Math.PI * 2);
    ctx.fill();
    
    // 绘制三条跑道
    for (let i = 0; i < 3; i++) {
        ctx.fillStyle = i % 2 === 0 ? '#A9A9A9' : '#D3D3D3';
        ctx.fillRect(i * LANE_WIDTH, 0, LANE_WIDTH, GAME_HEIGHT);
        
        // 绘制跑道分隔线
        if (i > 0) {
            ctx.strokeStyle = '#FFFFFF';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.moveTo(i * LANE_WIDTH, 0);
            ctx.lineTo(i * LANE_WIDTH, GAME_HEIGHT);
            ctx.stroke();
        }
    }
    
    // 绘制路面标记
    ctx.fillStyle = '#FFFFFF';
    for (let i = 0; i < 10; i++) {
        const y = (i * 80 + frameCount * GAME_SPEED) % GAME_HEIGHT;
        for (let j = 0; j < 3; j++) {
            ctx.fillRect(j * LANE_WIDTH + LANE_WIDTH / 2 - 5, y, 10, 40);
        }
    }
    
    // 绘制游戏物体
    cat.draw();
    chickens.forEach(chicken => chicken.draw());
    mcdonalds.forEach(mcdonald => mcdonald.draw());
    colas.forEach(cola => cola.draw());
    playerBullets.forEach(bullet => bullet.draw());
}

// 游戏循环
function gameLoop() {
    if (!gameRunning) return;
    
    frameCount++;
    spawnObjects();
    update();
    draw();
    
    requestAnimationFrame(gameLoop);
}

// 开始游戏
function startGame() {
    initGame();
    startScreen.classList.add('hidden');
    gameOverScreen.classList.add('hidden');
    canvasContainer.classList.remove('hidden');
    gameRunning = true;
    
    // 确保状态栏在游戏运行时可见
    statusBar.style.display = 'flex';
    
    gameLoop();
}

// 游戏结束
function gameOver() {
    gameRunning = false;
    finalScoreDisplay.textContent = score;
    canvasContainer.classList.add('hidden');
    gameOverScreen.classList.remove('hidden');
}

// 事件监听
startButton.addEventListener('click', startGame);
restartButton.addEventListener('click', startGame);

// 键盘控制
document.addEventListener('keydown', (e) => {
    if (!gameRunning) return;
    
    switch (e.key) {
        case 'ArrowLeft':
            cat.moveLeft();
            break;
        case 'ArrowRight':
            cat.moveRight();
            break;
        case ' ':
            const bullet = cat.shoot();
            if (bullet) {
                playerBullets.push(bullet);
            }
            break;
    }
});

// 移动端触摸控制
let touchStartX = 0;

canvas.addEventListener('touchstart', (e) => {
    if (!gameRunning) return;
    
    touchStartX = e.touches[0].clientX;
    e.preventDefault();
});

canvas.addEventListener('touchmove', (e) => {
    if (!gameRunning) return;
    
    const touchX = e.touches[0].clientX;
    const diffX = touchX - touchStartX;
    
    if (diffX > 30) {
        cat.moveRight();
        touchStartX = touchX;
    } else if (diffX < -30) {
        cat.moveLeft();
        touchStartX = touchX;
    }
    
    e.preventDefault();
});

canvas.addEventListener('touchend', (e) => {
    if (!gameRunning) return;
    
    const bullet = cat.shoot();
    if (bullet) {
        playerBullets.push(bullet);
    }
    
    e.preventDefault();
});

// 确保状态栏在初始状态可见
document.addEventListener('DOMContentLoaded', function() {
    statusBar.style.display = 'flex';
}); 